/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：GmudGame.java <br>
 * 创建时间：2013-5-20 下午4:21:44 <br>
 * 所属项目：GmudEX <br>
 *
 * @author 12548 <br>
 */
package lostland.gmud.exv2;

import java.util.ArrayList;
import java.util.Arrays;

import lostland.gmud.exv2.Gmud.PaymentData;
import lostland.gmud.exv2.Gmud.PaymentStatus;
import lostland.gmud.exv2.battle.BattleScreen;
import lostland.gmud.exv2.battle.proc.holder.Tournament;
import lostland.gmud.exv2.blgframework.CScreen;
import lostland.gmud.exv2.blgframework.Music;
import lostland.gmud.exv2.blgframework.impl.BLGGame;
import lostland.gmud.exv2.community.GmudUser;
import lostland.gmud.exv2.data.GameData;
import lostland.gmud.exv2.data.MainChar;
import lostland.gmud.exv2.data.Npc;
import lostland.gmud.exv2.data.Room;
import lostland.gmud.exv2.data.SaveData;
import lostland.gmud.exv2.data.TriggerScreen;
import lostland.gmud.exv2.expand.DesUtils;
import lostland.gmud.exv2.expand.FlyingScreen;
import lostland.gmud.exv2.expand.GmudPayment;
import lostland.gmud.exv2.ui.BlankScreen;
import lostland.gmud.exv2.ui.InventoryScreen;
import lostland.gmud.exv2.ui.LockedScreen;
import lostland.gmud.exv2.ui.MainMenuScreen;
import lostland.gmud.exv2.ui.NotificationScreen;
import lostland.gmud.exv2.ui.SkillScreen;
import lostland.gmud.exv2.ui.StatusScreen;
import lostland.gmud.exv2.ui.core.ButtonControlledScreen;
import lostland.gmud.exv2.ui.core.DialogScreen;
import lostland.gmud.exv2.ui.core.NewButton;
import lostland.gmud.exv2.ui.meta.CommunityActionDialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.update.BmobUpdateAgent;

import com.google.gson.Gson;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.tencent.mid.api.MidService;
import com.tencent.stat.StatConfig;
import com.tencent.stat.StatReportStrategy;
import com.tencent.stat.StatService;

/**
 * 类名：GmudGame <br>
 * 说明：游戏主活动
 *
 * @author 12548
 */
public class Game extends BLGGame {

	public String uname = "";

	public ArrayList<MainChar> oldmc = new ArrayList<>(5);
	public GameData data;
	public Tournament wulindahui = null;

	public boolean drawMap = false;
	public int mapX = 0;
	public int mapY = 0;
	public int mapDX = 0;
	public int mapDY = 0;

	public static boolean classickeymap = false;
	public static boolean backkeyquit = true;
	public static boolean soundEnabled = true;
	public static boolean uninterruptible = false;
	public static int resolution_level = 1;
	public static boolean autocheckupdate = true;
	public static boolean updateonlyonwifi = true;
	public static int bgm_level = 0;
	public static boolean autoAddFlyPoint = false;
	public static boolean menuKeyForFly = false;

	private Handler _handler = new GameMessageHandler();

	private static Game instance;

	public static Game getInstance() {
		return instance;
	}

	/**
	 * 多语言环境下的翻译
	 *
	 * @param resId R.string.XX
	 */
	public static String tr(int resId) {
		return instance.getString(resId);
	}

	public static GameData getData() {
		return instance.data;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		StatConfig.setMaxSendRetryCount(10);

		if(Gmud.DEBUG) {
			StatConfig.setStatSendStrategy(StatReportStrategy.INSTANT);
			StatConfig.setEnableStatService(false);
//			StatConfig.setDebugEnable(true);

			Logger
			.init("GMUD")
			.methodCount(3);

		} else {
			StatConfig.setDebugEnable(false);

			Logger.init("nolog").logLevel(LogLevel.NONE);

		}


		StatService.trackCustomEvent(this, "onCreate", "");
		Bmob.initialize(this, "66d77d30440b6d830111f26f7d074667"); // Bmob SDK


		if(instance != null && instance != this) {

			scene = instance.scene;
			if(scene.get(0) instanceof MapScreen) {
				MapScreen.setMs((MapScreen) scene.get(0));
			}

			_handler = instance.getHandler();
			data = instance.data;
			oldmc = instance.oldmc;
			wulindahui = instance.wulindahui;

			getCurrentScreen().resume();
		} else {
			data = new GameData();
			// xdata = new HashMap<String, Integer>();
		}

		instance = this;
		SharedPreferences sp = getFileIO().getPreferences();

		if(scene.isEmpty()) {
			MapScreen.setMs(new MapScreen());
			scene.add(MapScreen.getInstance());
			getStartScreen().pushToGame();
		}


		Game.classickeymap = sp.getBoolean("标准键位", true);
		Gmud.tileset = sp.getInt("图块", 2);
		NewButton.menubutton = sp.getBoolean("显示菜单键", false);
		Game.backkeyquit = sp.getBoolean("返回键退出", true);
		Game.uninterruptible = sp.getBoolean("不间断学习", false);
		Game.soundEnabled = sp.getBoolean("声音开关", true);
		NewButton.color = sp.getInt("按键颜色", 0);
		Game.resolution_level = sp.getInt("地图分辨率", 1);
		Game.autocheckupdate = sp.getBoolean("自动检查更新", true);
		Game.updateonlyonwifi = sp.getBoolean("只在wifi下更新", false);
		Game.bgm_level = sp.getInt("背景音乐等级", 0);
		Game.autoAddFlyPoint = sp.getBoolean("自动添加轻功点", false);
		Game.menuKeyForFly = sp.getBoolean("菜单键使用轻功", false);

		if(Game.autocheckupdate) {
			try {
				BmobUpdateAgent.update(this);
			} catch(Exception ignored) {
			}
		}

		String mid = MidService.getMid(this);

		if(!mid.equals("0")) { // mid已获取，否则不再继续检查

			Logger.d(mid);

			//先获取本地缓存的支付信息

			String payments = sp.getString(Gmud.PFKEY_PAYMENTDATA, "0");

//			logDebug("payments",payments);

			if(payments.equals("0")) return;

			try {
				final String decrypt = new DesUtils("awerfasd").decrypt(payments);

				Logger.d(decrypt);

				Gmud.paymentData = new Gson().fromJson(decrypt,
						PaymentData.class);

				//FIXME: 保存时要以相同的秘钥加密

				boolean flag_isPaid = false;


				for(final GmudPayment i : Gmud.paymentData.payments.values()) {

					Gmud.paymentData.paymentStatus = PaymentStatus.ZERO;

					String i_mid = i.getMid().getValue();

					if(!i.isMidValid()) {
						if(i_mid.equals("0") && i.getPaymentStatus().getValue().equals("SUCCESS")) { //TODO:支付时也以"0"为默认值
							i.getMid().setValue(mid); //善意地假设由于上次未成功而重新设置mid
						}
					}

					if(i_mid.equals(mid) && i.getPaymentStatus().getValue().equals("SUCCESS")) {
						Logger.d(i.getOrderID().getValue());
						flag_isPaid = true;
						uname = i.getName();
					}

					//TODO:更多检查
				}

				if(flag_isPaid) {
					//TODO 其他处理
					Gmud.paymentData.paymentStatus = PaymentStatus.PAID;

					Toast.makeText(this, String.format("非常感谢您的支持，尊敬的玩家%s。", uname), Toast.LENGTH_SHORT).show();
					Gmud.paymentData.paymentStatus = PaymentStatus.PAID;
				}


			} catch(Exception e) {
				if(Gmud.DEBUG) {
					e.printStackTrace();
				}
			}

		}

	}

	/**
	 * @param uname
	 */
	public void setRectangleStone(String uname) {
		new Room().item(175).desc(String.format("一块年代久远的长方形石板，上面刻着一行小字：我们对您感激于心，%s。", uname));
		if(Gmud.mc != null) {
			if(!Gmud.mc.have(175)) {
				Gmud.mc.give(175);
			}
		}
	}


	/*
	 * （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.IGame#getStartScreen()
	 */
	@Override
	public CScreen getStartScreen() {
		return new LoadingScreen();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		CScreen cs = getCurrentScreen();
		if(MapScreen.walking) return true;
		switch(keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if(cs instanceof MapScreen)
				if(backkeyquit) {
					new AlertDialog.Builder(this)
					.setTitle(Game.tr(R.string.exit_save))
					.setMessage(Game.tr(R.string.save_hint))
					.setPositiveButton(Game.tr(R.string.yes),
							new android.content.DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							new SavingScreen().save();
							new BlankScreen().pushToGame();
						}

					})
					.setNegativeButton(Game.tr(R.string.no),
							new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}

					}).show();
				} else {
					MainMenuScreen.getInstance().pushToGame();
				}
			else if(cs instanceof ButtonControlledScreen) {
				((ButtonControlledScreen) cs).onButtonClick(NewButton.NB_BACK);
			} else if(cs instanceof DialogScreen) {
				((DialogScreen) cs).onCancel();
			}
			break;
		case KeyEvent.KEYCODE_MENU:
		case KeyEvent.KEYCODE_ESCAPE:
			if(cs instanceof MapScreen) {
				if(menuKeyForFly) {
					FlyingScreen.fly();
				} else {
					MainMenuScreen.getInstance().pushToGame();
				}
			}
			break;
			// 外接键盘或手柄的按键模拟映射
		case KeyEvent.KEYCODE_DPAD_LEFT:
		case KeyEvent.KEYCODE_A:
			if(cs instanceof MapScreen) {
				((MapScreen) cs).onButtonClick(NewButton.NB_LEFT);
			} else if(cs instanceof ButtonControlledScreen) {
				((ButtonControlledScreen) cs).onButtonClick(NewButton.NB_LEFT);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
		case KeyEvent.KEYCODE_D:
			if(cs instanceof MapScreen) {
				((MapScreen) cs).onButtonClick(NewButton.NB_RIGHT);
			} else if(cs instanceof ButtonControlledScreen) {
				((ButtonControlledScreen) cs).onButtonClick(NewButton.NB_RIGHT);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_UP:
		case KeyEvent.KEYCODE_W:
			if(cs instanceof MapScreen) {
				((MapScreen) cs).onButtonClick(NewButton.NB_UP);
			} else if(cs instanceof ButtonControlledScreen) {
				((ButtonControlledScreen) cs).onButtonClick(NewButton.NB_UP);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
		case KeyEvent.KEYCODE_S:
			if(cs instanceof MapScreen) {
				((MapScreen) cs).onButtonClick(NewButton.NB_DOWN);
			} else if(cs instanceof ButtonControlledScreen) {
				((ButtonControlledScreen) cs).onButtonClick(NewButton.NB_DOWN);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_CENTER:
		case KeyEvent.KEYCODE_SPACE:
		case KeyEvent.KEYCODE_ENTER:
			if(cs instanceof MapScreen) {
				((MapScreen) cs).onButtonClick(NewButton.NB_ENTER);
			} else if(cs instanceof ButtonControlledScreen) {
				((ButtonControlledScreen) cs).onButtonClick(NewButton.NB_ENTER);
			}
			break;
			// 状态、物品、轻功等的快捷键
		case KeyEvent.KEYCODE_F1:
			if(cs instanceof MapScreen) {
				new StatusScreen().pushToGame();
			}
			break;
		case KeyEvent.KEYCODE_F2:
			if(cs instanceof MapScreen) {
				new InventoryScreen(false, cs).pushToGame();
			}
			break;
		case KeyEvent.KEYCODE_F3:
			if(cs instanceof MapScreen) {
				new SkillScreen(cs).pushToGame();
			}
			break;
		case KeyEvent.KEYCODE_F4:
			if(cs instanceof MapScreen) {
				FlyingScreen.fly();
			}
			break;
		case KeyEvent.KEYCODE_F5:
			if(cs instanceof MapScreen) {
				new SavingScreen().pushToGame();
			}
			break;
		default:
//				if (cs instanceof DialogScreen) {
//					cs.update(0);
//				}
			break;
		}

		return false;
	}


	/*
	 * （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.impl.BLGGame#onResume()
	 */
	@Override
	public void onResume() {
		super.onResume();
		playBGM();
	}

	@Override
	public void onPause(){
		super.onPause();
		stopBGM();
	}


	public Handler getHandler() {
		if(_handler == null) {
			_handler = new GameMessageHandler();
		}
		return _handler;
	}

	public void callTriggerEvent(int eventid, boolean _boolArg, int _intArg1, int _intArg2,
			float _floatArg,
			String _strArg, int _currentLine) {

		for(int i : Gmud.events.get(eventid).conditions) {
			if(!Gmud.conditions.get(i).check()) return;
		}

		new TriggerScreen(Gmud.events.get(eventid), _currentLine, _boolArg, _intArg1,
				_intArg2, _floatArg,
				_strArg).pushToGame();
	}

	/**
	 * 结婚
	 */
	public static void propose_process() {
		new CommunityActionDialog(getInstance(), "请输入你要与之结婚的玩家用户名") {

			@Override
			public void execute(GmudUser user) {
				String s = user.getSaveObjectID();
				if(s.equals("")) {
					new NotificationScreen("对方并无云存档！").replaceCurrent();
				}

				new LockedScreen("正在获取对方玩家信息，请稍候。。。").pushToGame();
				BmobQuery<SaveData> q = new BmobQuery<>();
				q.getObject(getInstance(), s, new GetListener<SaveData>() {

					@Override
					public void onFailure(int arg0, String arg1) {
						new NotificationScreen("获取对方存档信息失败！").replaceCurrent();
					}

					@Override
					public void onSuccess(SaveData arg0) {
						MainChar spouse = arg0.mc;
						if(Gmud.mc.sex + spouse.sex != 1) {
							new NotificationScreen("你们的性别不适合结婚！").replaceCurrent();
							return;
						} else if(Math.abs(Gmud.mc.age - spouse.age) > 20 || spouse.age < 20) {
							new NotificationScreen("你们的年龄不适合结婚！").replaceCurrent();
							return;
						} else if(spouse.faction == 8) {
							new NotificationScreen("对方所在的门派禁止结婚！").replaceCurrent();
							return;
						} else {
							new NotificationScreen("结婚成功！你的配偶将出现在家中。").replaceCurrent();
							GameEvent.doMarriage(arg0);
						}


					}
				});
			}
		}.show();
	}

	/**
	 * 切磋
	 */
	public static void qiecuo_process() {
		new CommunityActionDialog(getInstance(), "请输入你要与之切磋的玩家用户名") {

			@Override
			public void execute(GmudUser user) {
				String s = user.getSaveObjectID();
				if(s.equals("")) {
					new NotificationScreen("对方并无云存档！").replaceCurrent();
				}

				new LockedScreen("正在获取对方玩家信息，请稍候。。。").pushToGame();
				BmobQuery<SaveData> q = new BmobQuery<>();
				q.getObject(getInstance(), s, new GetListener<SaveData>() {

					@Override
					public void onFailure(int arg0, String arg1) {
						new NotificationScreen("获取对方存档信息失败！").replaceCurrent();
					}

					@Override
					public void onSuccess(SaveData arg0) {
						MainChar spouse = arg0.mc;
						int id = new Room().npc(spouse)
								.introduction("")
								.flag(Npc.FLAG_NODROP)
								.flag(Npc.FLAG_IMPORTANT)
								.look(-1, -1)
								.say("请指教！").id;

						getInstance().popToRootScreen();
						BattleScreen.battle(id);

					}
				});
			}
		}.show();
	}


	public Music getBGM() {
		//TODO: Multi bgm
		return Assets.bgm;
	}

	public boolean isBGMPlaying() {
		if(getBGM() == null) return false;
		return getBGM().isPlaying();
	}

	public void setBGMVolume(float volume) {
		if(getBGM() == null) return;
		getBGM().setVolume(volume);
	}

	public void playBGM() {
		if(getBGM() == null || bgm_level == 0) return;
		getBGM().play();
	}

	public void stopBGM() {
		if(getBGM() == null) return;
		getBGM().pause();
	}

	public void refreshBGMVolume() {
		final float[] vol = {0, 0.2f, 0.5f, 1f};
		setBGMVolume(vol[bgm_level]);
	}

	public void changeBGM(Music newbgm) {

		if(Assets.bgm == newbgm) return;

		stopBGM();
		Assets.bgm = newbgm;
		refreshBGMVolume();
		playBGM();
	}

	public void popToRootScreen() {
		while(scene.size() > 1) {
			popScreen();
		}
		if(!(scene.get(0) instanceof MapScreen)) {
			MapScreen.getInstance().replaceCurrent();
		}
	}

	/**
	 * @deprecated 请使用screen.pushToGame代理。
	 */
	@Deprecated
	public void pushScreen(CScreen screen) {
		CScreen scrb = getCurrentScreen();
		if(scene.size() > 0) {
			getCurrentScreen().pause();
		}
		if(screen == MapScreen.getInstance()) {
			popToRootScreen();
			return;
		}
		screen.resume();
		scene.add(screen);

		if(screen instanceof ButtonControlledScreen && !(scrb instanceof ButtonControlledScreen)) {
			Arrays.fill(NewButton.pressed, false);
			ButtonControlledScreen.refreshButtons();
		}
	}

	/**
	 * @deprecated 请使用screen.replaceCurrent代理。
	 */
	@Deprecated
	public void replaceCurrentScreen(CScreen screen) {
		if(scene.size() == 1 && scene.get(0) == MapScreen.getInstance())
			throw new RuntimeException("根场景不能被替换！");
		if(screen == MapScreen.getInstance()) {
			popToRootScreen();
			return;
		}
		CScreen scrb = getCurrentScreen();

		getCurrentScreen().npause();
		getCurrentScreen().dispose();

		scene.remove(scene.size() - 1);
		screen.pushToGame();

		CScreen scr = screen;
		if(scr instanceof ButtonControlledScreen && !(scrb instanceof ButtonControlledScreen)) {
			Arrays.fill(NewButton.pressed, false);
			ButtonControlledScreen.refreshButtons();
		}
	}

	/* （非 Javadoc）
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		super.onStop();
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.impl.BLGGame#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void callPay(double price) {
		Intent intent = new Intent(this, PaymentActivity.class);
		intent.putExtra("price", price);
		this.startActivityForResult(intent, 0);
	}

}
